package com.cloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.cloud.config.ConsumerLogProperties;
import com.cloud.entity.SysLog;
import com.cloud.mapper.SysLogMapper;
import com.cloud.service.SyncSysLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SyncSysLogServiceImpl implements SyncSysLogService {
    //全局list，消费者相当于多线程，当达到一定数量批量插入
    private static List<SysLog> syslogs = new ArrayList<>();
    @Autowired
    private ConsumerLogProperties consumerLogProperties;
    @Autowired
    private SysLogMapper sysLogMapper;

    @Override
    public void manualBatchSave() {
        List<SysLog> sysLogTem;
        synchronized (SyncSysLogServiceImpl.class) {
            sysLogTem = syslogs;
            syslogs = new ArrayList<>();
        }
        if (!CollectionUtils.isEmpty(sysLogTem)) {
            sysLogMapper.batchInsert(sysLogTem);
        }
    }

    @Override
    public void receiveLogRecord(SysLog sysLog) {
        List<SysLog> sysLogTem = null;
        synchronized (SyncSysLogServiceImpl.class) {
//            EntityUtil.setCreatAndUpdateInfo(sysLog);
            syslogs.add(sysLog);
            if (syslogs.size() >= consumerLogProperties.getBatchSize()) {
                log.info("批量list的长度：：" + consumerLogProperties.getBatchSize());
                sysLogTem = syslogs;
                syslogs = new ArrayList<>();
            }
        }
        try {
            if (!CollectionUtils.isEmpty(sysLogTem)) {
                sysLogMapper.batchInsert(sysLogTem);
            }
        } catch (Exception e) {
            log.error("读取日志错误,源信息:" + JSON.toJSONString(syslogs));
            log.error("读取日志错误:", e);
        }
    }
}
